import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { Table, Spin, Form, Row, Col, Input, Button, Dropdown, Menu, Icon, message, Modal, Select, Tree, TreeSelect, DatePicker, Checkbox, Tabs, InputNumber } from 'antd'
import _ from 'lodash'
import moment from 'moment'

import Ajax from 'lib/Ajax'
import { addConfig } from 'actions/config'
import { getNewTreeData, findRowData, getNameByCode, getYear, getPayCycleDom, getStringByType, getNameByState, confirmDelete, downloadFile } from 'lib/fun'
import ShowCitizen from './showCitizen'

const TreeNode = Tree.TreeNode;
const Option = Select.Option;
const FormItem = Form.Item;
const TabPane = Tabs.TabPane;

class ModuleName extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      data: [],
      batchList: [],
      batchNull: false,
      visible: false,
      rowdata: {}
    }
    this.current = 1;   //当前第几页
    this.total = 10;   //总共多少页
    this.pageSize = 10;   //每页多少行
    this.search = {};
  }

  componentDidMount(){
  }

  componentWillReceiveProps(nextProps){
    if(!nextProps.visible){
      this.props.form.resetFields();
      this.current = 1;   //当前第几页
      this.total = 10;   //总共多少页
      this.pageSize = 10;
      this.setState({
        batchList: [],
        batchNull: false,
        loading: false
      });
    }else if(this.state.batchList.length == 0){
      this.loadBatch();
    }
  }

  loadBatch = ()=>{
    var self = this
    if (this.state.loading) {
      return
    }
    this.setState({
      loading: true
    });
    Ajax({
      url: this.props.uploadBatchList,
      data: {},
      success: function(data){
        if(data&&data.length>0){
          self.setState({
            loading: true,
            batchList: data
          });
          self.search.batchId = data[0].batchId;
          self.loadData();
        }else{
          self.setState({
            loading: false,
            batchNull: true
          });
        }
      },
      error: function(error){
        self.setState({
          loading: false
        });
        message.error(error);
      }
    });
  }

  pageOnChange = (page)=>{
    this.current = page;
    this.loadData();
  }

  showSizeChange = (current, pageSize)=>{
    var page = Math.ceil(((this.current-1)*this.pageSize+1)/pageSize);
    this.pageSize = pageSize;
    this.current = page;
    this.loadData();
  }

  loadData = (props) => {
    var self = this;
    self.setState({
      loading: true
    });
    const { identNumber, name, batchId } = this.search;
    Ajax({
      url: this.props.failList,
      data: {
        identNumber,
        name,
        currentPage: self.current,  //请求页码
        perPage: self.pageSize,   //每页数量
        batchId
      },
      success: function(data){
        self.total = data.totalCount;
        self.setState({
          loading: false,
          data: data.list
        });
      },
      error: function(error){
        self.setState({
          loading: false
        });
        message.error(error);
      }
    });
  }

  handleSearch = (option)=>{
    var option = this.props.form.getFieldsValue();
    if(!_.isEqual(option, this.search)){
      this.search = option;
      this.loadData();
    }
  }

  onCancel = ()=>{
    this.setState({
      loading: false
    });
    this.props.onClose();
  }

  operate = (row)=>{
    this.setState({
      visible: true,
      rowdata: row
    });
  }

  downloadError = ()=>{
    var self = this;
    if(!self.search.batchId){
      return
    }
    self.setState({
      loading: true
    });
    downloadFile(this.props.downFailList, {
      batchId: self.search.batchId
    }, {
      end: ()=>{
        self.setState({
          loading: false
        });
      }
    });
  }

  renderFilter = ()=>{
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 10 },
      wrapperCol: { span: 14 },
    };
    return (<div className="ant-advanced-search-form">
          <Form
            horizontal
          >
          <Row>
            <Col span={6}>
              <FormItem {...formItemLayout} label="批次编号">
                {getFieldDecorator("batchId", {
                  initialValue: this.state.batchList&&this.state.batchList.length>0?this.state.batchList[0].batchId:""
                })(
                  <Select
                    size="default"
                  >
                    {
                      (this.state.batchList||[]).map(function(obj){
                        return (<Option key={obj.batchId+""} value={ obj.batchId+"" }>{ obj.createTime }</Option>)
                      })
                    }
                  </Select>
                )}
              </FormItem>
            </Col>
            {
              this.props.type=="upload"?<Col span={6}>
              <FormItem {...formItemLayout} label="用户姓名">
                {getFieldDecorator("name")(
                  <Input />
                )}
              </FormItem>
            </Col>:""
            }
            <Col span={6}>
              <FormItem {...formItemLayout} label="身份证">
                {getFieldDecorator("identNumber")(
                  <Input />
                )}
              </FormItem>
            </Col>
            <Col span={6}>
              <div className="btn-group">
                <Button type="primary" onClick={this.handleSearch} style={{marginRight:10}}>查询</Button>
                <Button type="primary" onClick={this.downloadError} disabled={!this.search.batchId}>下载失败人员信息</Button>
              </div>
            </Col>
          </Row>
          </Form>
        </div>);
  }

  renderPeople = ()=>{
    var self = this;
    const { bankCode } = this.props.config;

    const { config, common, see, type, visible } = this.props;
    if(type == 'upload'){
      var columns = [{
        title: '用户姓名',
        dataIndex: 'name'
      }, {
        title: '证件号码',
        dataIndex: 'identNumber'
      }, {
        title: '民族',
        dataIndex: 'nationName',
        // render: (text, record) => (<span>{ getNameByCode(config, 'nationCode', text) }</span>)
      }, {
        title: '是否户主',
        dataIndex: 'master',
        render: (text, record) => (<span>{ text?"是":"否" }</span>)
      }, {
        title: '户口簿编号',
        dataIndex: 'householdRegisterNumber'
      }, {
        title: '行政区划',
        dataIndex: 'areaName'
      }, {
          title: '操作',
          key: 'action',
          render: (text, record) => (<a onClick={this.operate.bind(this, record)} href="javascript:;">查看</a>)
      }];
    }else if(type == 'uploadArea'){
      var columns = [{
        title: '批次id',
        dataIndex: 'batchId'
      }, {
        title: '证件号码',
        dataIndex: 'identNumber'
      }, {
        title: '区划代码',
        dataIndex: 'newAreaCode'
      }, {
        title: '处理失败原因',
        dataIndex: 'failReason'
      }, {
        title: '时间',
        dataIndex: 'createTime'
      }];
    }else if(type == 'uploadName'){
      var columns = [{
        title: '批次id',
        dataIndex: 'batchId'
      }, {
        title: '证件号码',
        dataIndex: 'identNumber'
      }, {
        title: '用户姓名',
        dataIndex: 'name'
      }, {
        title: '处理失败原因',
        dataIndex: 'failReason'
      }, {
        title: '时间',
        dataIndex: 'createTime'
      }];
    }else{
      var columns = [{
        title: '批次id',
        dataIndex: 'batchId'
      }, {
        title: '证件号码',
        dataIndex: 'identNumber'
      }, {
        title: '银行名字',
        dataIndex: 'bankName'
      }, {
        title: '银行卡号',
        dataIndex: 'bankNumber'
      }, {
        title: '处理失败原因',
        dataIndex: 'failReason'
      }, {
        title: '时间',
        dataIndex: 'createTime'
      }];
    }

    var pagination = {
      current: this.current,
      total: this.total,
      pageSize: this.pageSize,
      onChange: this.pageOnChange,
      showSizeChanger: true,
      onShowSizeChange: this.showSizeChange,
      showTotal: total => `总共 ${total} 条`
    };

    return (
        <div style={{marginTop: 15}}>
          <Table 
            columns={columns}
            loading={this.state.loading}
            dataSource={ this.state.data }
            rowKey="id"
            pagination={ pagination }
          />
        </div>
    )
  }

  render() {
    const { visible, type, title } = this.props;
    
    return (<Modal 
              title={ title }
              visible={visible}
              onOk={ this.onCancel } 
              onCancel={ this.onCancel }
              okText="确定"
              cancelText="取消"
              width="1100px"
            >
              { this.renderFilter() }
              { this.renderPeople() }
              <ShowCitizen
                visible={this.state.visible}
                rowdata={this.state.rowdata}
                onCancel={()=>{
                  this.setState({
                    visible: false
                  });
                }}
                url={this.props.getFail}
                type={this.props.type}
              />
            </Modal>
            );
  }
}

function mapStateToProps(state) {
  return {
    config: state.config
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ addConfig }, dispatch)
}

module.exports = connect(mapStateToProps,mapDispatchToProps)(Form.create()(ModuleName))